package com.ning.weixin.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ning.weixin.controller.AcApiResponse;
import com.ning.weixin.controller.AcApiResponsePage;
import com.ning.weixin.dao.AcInfoDao;
import com.ning.weixin.dao.AcLocationDao;
import com.ning.weixin.dao.AcMemberDao;
import com.ning.weixin.dao.AcPunchDao;
import com.ning.weixin.dao.AcQrcodeDao;
import com.ning.weixin.dao.AcQueryDao;
import com.ning.weixin.dao.AcShareLogDao;
import com.ning.weixin.dao.AcWechatInfoDao;
import com.ning.weixin.entity.AcLocation;
import com.ning.weixin.entity.AcMember;
import com.ning.weixin.entity.AcPunch;
import com.ning.weixin.entity.AcQrcode;
import com.ning.weixin.entity.AcShareLog;
import com.ning.weixin.entity.AcWechatInfo;
import com.ning.weixin.service.AcApiService;
import com.ning.weixin.utils.ScoreUtil;

/**
 * @author MENG_LI_DONG
 * @version 2018年12月18日 下午10:44:34
 */
@Transactional
@Service
public class AcApiServiceImpl implements AcApiService{
	private Logger log = LoggerFactory.getLogger(AcApiServiceImpl.class);
	@Autowired
	private AcMemberDao memberDao;
	@Autowired
	private AcWechatInfoDao wechatInfoDao;
	@Autowired
	private AcLocationDao locationDao;
	@Autowired
	private AcPunchDao punchDao;
	@Autowired
	private AcShareLogDao shareLogDao;
	@Autowired
	private AcQueryDao queryDao;
	@Autowired
	private AcInfoDao infoDao;
	@Autowired
	private AcQrcodeDao qrcodeDao;
	@Override
	public void saveWechatInfo(AcWechatInfo t) {
		AcWechatInfo record = wechatInfoDao.getByOpenid(t.getOpenid());
		if(record==null){
			AcMember mem = new AcMember();
			mem.setOpenid(t.getOpenid());
			mem.setAvatar(t.getHeadimgurl());
			long userId = memberDao.insertReturnId(mem);
			t.setUserId(userId);
			try {
				String nickname = URLEncoder.encode(t.getNickname(),"utf-8");
				t.setNickname(nickname);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				log.debug("昵称转码失败");
				e.printStackTrace();
			}
			wechatInfoDao.insert(t);
		}
	}
	@Override
	public AcApiResponse punchActivity(String openid, String location) {
		Map<String,Object> map = new HashMap<String, Object>();
		AcApiResponse api = new AcApiResponse("0", "success", map);
		if(infoDao.isExpire(0L)){
			api.setCode("999");
			api.setMsg("活动已结束");
			return api;
		}
		AcWechatInfo winfo = wechatInfoDao.getByOpenid(openid);
		
		if(winfo == null){
			api.setCode("1");
			api.setMsg("非法的openid");
			return api;
		}
		AcLocation loc = locationDao.getByFlag(location);
		if(loc == null){
			api.setCode("1");
			api.setMsg("场地不存在");
			return api;
		}
		List<Map<String,Object>> todayPunchList = queryDao.getTodayPunchList(openid,loc.getId());
		if(todayPunchList.isEmpty()) { //今日没签到，可签到
			api.setCode("0");
			api.setMsg("成功");
	        Integer score = ScoreUtil.scoreGet();
			map.put("score", score);
			map.put("signNums", 1);
			AcPunch punch = new AcPunch();
			punch.setCreateTime(new Date());
			punch.setLocationId(loc.getId());
			punch.setOpenid(openid);
			punch.setScore(score);
			punch.setUpdateTime(punch.getCreateTime());
			punch.setUserId(winfo.getUserId());
			punchDao.insert(punch);
			return api;
		} else if(todayPunchList.size() == 1) {//已签到，看今天有没有分享有
			int shareCount = queryDao.getTodayShareCount(openid, loc.getId());
			if(shareCount>0){ // 已分享，可签到
				api.setCode("0");
				api.setMsg("成功");
		        Integer score = ScoreUtil.scoreGet();
				map.put("score", score);
				map.put("signNums", 2);
				AcPunch punch = new AcPunch();
				punch.setCreateTime(new Date());
				punch.setLocationId(loc.getId());
				punch.setOpenid(openid);
				punch.setScore(score);
				punch.setUpdateTime(punch.getCreateTime());
				punch.setUserId(winfo.getUserId());
				punchDao.insert(punch);
				return api;
			} else {
				api.setCode("1");
				api.setMsg("您的"+loc.getName()+"打卡次数不足，请先转发获取"+loc.getName()+"打卡次数");
				return api;
			}
		} else {
			api.setCode("1");
			api.setMsg("您今日"+loc.getName()+"打卡次数已用完,请明天再来!");
			return api;
		}
	}
	@Override
	public AcApiResponse getUserInfo(String openid) {
		AcWechatInfo winfo = wechatInfoDao.getByOpenid(openid);
		Map<String,Object> map = new HashMap<String, Object>();
		AcApiResponse api = new AcApiResponse("0", "success", map);
		if(winfo == null){
			api.setCode("1");
			api.setMsg("非法的openid");
			return api;
		}
		try {
			String nickname = URLDecoder.decode(winfo.getNickname(), "UTF-8");
			winfo.setNickname(nickname);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			log.debug("GET昵称转码失败");
			e.printStackTrace();
		}
		map.put("id", winfo.getId());
		map.put("openid", openid);
		map.put("nickname", winfo.getNickname());
		map.put("headimgurl", winfo.getHeadimgurl());
		map.put("province", winfo.getProvince());
		map.put("city", winfo.getCity());
		map.put("country", winfo.getCountry());
		map.put("sex", winfo.getSex());
		Map<String,Object> activityLive = new HashMap<>();
		map.put("activityLive", activityLive);
		map.put("isExpire", infoDao.isExpire(0L));
		Map<String,Object> rank = queryDao.getRankByOpenid(openid);
		if(rank==null){
			activityLive.put("totalScores", 0);
			activityLive.put("ranking", 0);
			activityLive.put("signInNums", 0);
		} else {
			activityLive.put("totalScores", rank.get("total_scores"));
			activityLive.put("ranking", rank.get("rank_num"));
			activityLive.put("signInNums", rank.get("sign_in_nums"));
		}
		activityLive.put("punchList", queryDao.getPunchList(openid));
		return api;
	}
	@Override
	public AcApiResponse shareCallback(String openid, String location) {
		AcWechatInfo winfo = wechatInfoDao.getByOpenid(openid);
		Map<String,Object> map = new HashMap<String, Object>();
		AcApiResponse api = new AcApiResponse("0", "success", map);
		if(winfo == null){
			api.setCode("1");
			api.setMsg("非法的openid");
			return api;
		}
		AcLocation loc = locationDao.getByFlag(location);
		if(loc == null){
			api.setCode("1");
			api.setMsg("场地不存在");
			return api;
		}
		List<Map<String,Object>> todayPunchList = queryDao.getTodayPunchList(openid,loc.getId());
		if(todayPunchList.isEmpty()) { //无效分享
			api.setCode("0");
			api.setMsg("成功");
			map.put("remainingSignNum", 0);
			return api;
		}
		if(todayPunchList.size() == 1){ // 已打卡一次，可以分享且数量加1
			AcShareLog share = new AcShareLog();
			share.setCreateTime(new Date());
			share.setLocationId(loc.getId());
			share.setOpenid(openid);
			share.setUpdateTime(share.getCreateTime());
			share.setUserId(winfo.getUserId());
			shareLogDao.insert(share);
			api.setCode("0");
			api.setMsg("分享成功，多一次打卡机会");
			map.put("remainingSignNum", 1); //分享成功，多一次打卡机会
			return api;
		} else {
			api.setCode("1");
			api.setMsg("您已分享过了,打卡次数不累加");
			map.put("remainingSignNum", 0);
			return api;
		}
	}
	@Override
	public AcApiResponsePage getRanks(String openid, Integer pageIndex,
			Integer pageSize) {
		if(pageIndex==null){
			pageIndex = 0;
		}
		if(pageIndex<=0){
			pageIndex = 0;
		}
		if(pageSize == null) {
			pageSize = 10;
		}
		if(pageSize<=0){
			pageIndex = 10;
		}
		List<Map<String,Object>> list = queryDao.getRanksByPage(pageIndex, pageSize);
		List<Map<String,Object>> res = new ArrayList<Map<String,Object>>();
		for(Map<String,Object> map:list){
			Map<String,Object> m = new HashMap<>();
			m.put("openid", map.get("openid"));
			m.put("rankNum", map.get("rank_num"));
			m.put("avatar", map.get("headimgurl"));
			try{
				String nickname = (String)map.get("nickname");
				nickname = URLDecoder.decode(nickname, "UTF-8");
				m.put("nickname", nickname);
			} catch(Exception e) {
				log.debug("GETRanks昵称转码失败");
				e.printStackTrace();
			}
			m.put("totalScores", map.get("total_scores"));
			m.put("signInNums", map.get("sign_in_nums"));
			res.add(m);
		}
		int rows = queryDao.getRanksByPageCount();
		int pageCount = 0;
		 if (rows % pageSize == 0) {
			 pageCount = rows / pageSize;
	        } else {
	        	pageCount = rows / pageSize + 1;
	        }
		return new AcApiResponsePage("0", pageCount, rows, "success", res);
	}
	@Override
	public AcApiResponse saveContact(String openid, String realname,
			String phone) {
		AcWechatInfo winfo = wechatInfoDao.getByOpenid(openid);
		Map<String,Object> map = new HashMap<String, Object>();
		AcApiResponse api = new AcApiResponse("0", "success", map);
		if(winfo == null){
			api.setCode("1");
			api.setMsg("非法的openid");
			return api;
		}
		memberDao.updateRealnameAndPhoneByOpenid(openid, realname, phone);
		return new AcApiResponse("0","success", new HashMap<>());
	}
	@Override
	public AcApiResponse createQrcode(String locNo, String deviceNo) {
		Map<String,Object> map = new HashMap<String, Object>();
		AcApiResponse api = new AcApiResponse("0", "success", map);
		AcQrcode qr = new AcQrcode();
		qr.setCreateTime(new Date());
		qr.setDeviceNo(deviceNo);
		qr.setLocNo(locNo);
		qr.setState(0);
		qrcodeDao.insert(qr);
		map.put("id", qr.getId());
		return api;
	}
	@Override
	public AcApiResponse getQrcode(String id) {
		Map<String,Object> map = new HashMap<String, Object>();
		AcApiResponse api = new AcApiResponse("0", "success", map);
		AcQrcode t = qrcodeDao.get(id);
		if(t==null){
			api.setCode("1");
			api.setMsg("二维码不存在");
			return api;
		}
		// 15*60*1000 == 十五分钟过期
		Date currentData = new Date();
		if(currentData.getTime()-t.getCreateTime().getTime()>900000){
			api.setCode("2");
			api.setMsg("二维码已过期");
			return api;
		}
		map.put("id", t.getId());
		map.put("deviceNo", t.getDeviceNo());
		map.put("locNo", t.getLocNo());
		return api;
	}

}
